﻿// Copyright 2009 Mike Geise
// 
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// 
//     http://www.apache.org/licenses/LICENSE-2.0
// 
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

namespace Falcon.Core.Extensions
{
	using System;
	using System.Globalization;

	public static class ObjectExtension
	{
		/// <summary>
		/// Converts the value.
		/// </summary>
		/// <typeparam name="T"></typeparam>
		/// <param name="value">The value.</param>
		/// <returns></returns>
		public static T As<T>(this object value)
		{
			return (value != null && value is T) ? (T)value : default(T);
		}

		/// <summary>
		/// Converts the string value to int.
		/// </summary>
		/// <param name="value">The value.</param>
		/// <returns></returns>
		public static int AsInt(this string value)
		{
			if (value.HasValue())
			{
				int result;

				var success = int.TryParse(value, NumberStyles.Integer, CultureInfo.InvariantCulture, out result);

				if (success)
				{
					return result;
				}
			}

			return 0;
		}

		/// <summary>
		/// Converts the string value to boolean.
		/// </summary>
		/// <param name="value">The value.</param>
		/// <returns></returns>
		public static bool AsBoolean(this string value)
		{
			if (value.HasValue())
			{
				bool result;

				var success = bool.TryParse(value, out result);

				if (success)
				{
					return result;
				}
			}

			return false;
		}

		/// <summary>
		/// Converts the string value to Guid.
		/// </summary>
		/// <param name="value">The value.</param>
		/// <returns></returns>
		public static Guid AsGuid(this string value)
		{
			return value.HasValue() ? new Guid(value) : Guid.Empty;
		}
	}
}